package com.example.star.controller;

import com.example.star.entity.BuyNow;
import com.example.star.entity.User;
import com.example.star.service.BuyNowService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class BuyNowController {

    @Autowired
    private BuyNowService buyNowService;

    @PostMapping("/buy_nows")
    @ResponseBody
    public BuyNow saveBuyNow(@RequestBody BuyNow buyNow) {
        buyNowService.saveBuyNow(buyNow);
        return buyNow; // 返回保存的ShoppingCart对象
    }

    @GetMapping("/buy_nows")
    @ResponseBody
    public List<BuyNow> getBuyNows() {
        return buyNowService.getAllBuyNows();
    }

    @GetMapping("/buy_nows/items-by-user")
    @ResponseBody
    public List<BuyNow> getBuyNowByUserId(@RequestParam String userName){
        return buyNowService.getBuyNowByuserName(userName);
    }

    @GetMapping("/buy_nows/items-by-orderStatus")
    @ResponseBody
    public List<BuyNow> getBuyNowByOrderStatus(@RequestParam String orderStatus){
        return buyNowService.getBuyNowByOrderStatus(orderStatus);
    }

    @PostMapping("/buy_nows/updateOrderStatus")
    @ResponseBody
    public BuyNow updateOrderStatus(@RequestParam int id, @RequestParam String orderStatus) {
        return buyNowService.updateOrderStatus(id, orderStatus);
    }

    @GetMapping("/buy_nows/items-by-user-and-status")
    @ResponseBody
    public List<BuyNow> getBuyNowsByUserIdAndOrderStatus(@RequestParam String userName, @RequestParam String orderStatus) {
        return buyNowService.getBuyNowsByuserNameAndOrderStatus(userName, orderStatus);
    }

    @DeleteMapping("/buy_nows/{id}")
    @ResponseBody
    public void deleteBuyNowById(@PathVariable int id){
        buyNowService.deleteBuyNowById(id);
    }

    @PostMapping("/buy_nows/submit_evaluation/{id}")
    @ResponseBody
    public String submitEvaluation(@PathVariable int id,
                                   @RequestParam("rating") float rating,
                                   @RequestParam("comment") String comment) {
        return buyNowService.submitEvaluation(id, rating, comment);
    }

    @ResponseBody
    @DeleteMapping("/buy_nows/order/{id}")
    public void deleteOrder(@PathVariable int id) {
        buyNowService.deleteOrder(id);
    }

    @GetMapping("/buynow-list")
    public String showBuyNowList(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "8") int size,
                                 Model model,
                                 HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            // 用户未登录，重定向到登录页面
            return "redirect:/login";
        }
        User user = (User) userObj;
        List<BuyNow> buyNows;
        int totalOrders;
        if ("ADMIN".equals(user.getRole())) {
            // 管理员角色，获取所有订单信息
            buyNows = buyNowService.getBuyNowByPage(page, size);
            totalOrders = buyNowService.getTotalBuyNows();
        } else {
            // 普通用户角色，获取该用户的订单信息
            buyNows = buyNowService.getBuyNowsByUserName(user.getUsername(), page, size);
            totalOrders = buyNowService.getTotalBuyNowsByUserName(user.getUsername());
        }
        int totalPages = (int) Math.ceil((double) totalOrders / size);

        model.addAttribute("buy_nows", buyNows);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "buynow-list";
    }

    @PostMapping("/buy_nows/{id}")
    public String deleteBuyNows(@PathVariable int id, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        // 从 HttpSession 中获取用户信息
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            redirectAttributes.addFlashAttribute("error", "你还未登录，请先登录");
            return "redirect:/login"; // 重定向到登录页面
        }

        User user = (User) userObj;
        // 假设管理员角色名称为 "ADMIN"，根据实际情况修改
        if ("ADMIN".equals(user.getRole())) {
            try {
                buyNowService.deleteBuyNowById(id);
                redirectAttributes.addFlashAttribute("message", "购物车信息删除成功");
            } catch (Exception e) {
                redirectAttributes.addFlashAttribute("error", "删除购物车信息时出现错误：" + e.getMessage());
            }
        } else {
            redirectAttributes.addFlashAttribute("error", "你没有权限删除购物车信息");
        }
        return "redirect:/buynow-list";
    }



}
